package com.cipe.cmrs.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cipe.cmrs.dao.BaseRefDao;
import com.cipe.cmrs.model.RestrictedUiElements;
import com.cipe.cmrs.model.Role;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.RestrictedUiElementsService;

@Service
public class RestrictedUiElementsServiceImpl implements RestrictedUiElementsService {
    @Autowired
    private BaseRefDao dao;

    @SuppressWarnings("unchecked")
    public Map<String, Map<String, String>> getAllAllowedUiElements(User user) {
        Map<String, Map<String, String>> results = new HashMap<String, Map<String, String>>();
        List<Integer> values = new ArrayList<Integer>();
        StringBuilder builder = new StringBuilder("FROM RestrictedUiElements");
        if (user.getRoles().size() > 0) {
            builder.append(" WHERE pk.roleId IN (");
            List<Role> roles = new ArrayList<Role>(user.getRoles());
            int i = 1;
            for (; i < roles.size(); i++) {
                builder.append("?" + i + ",");
                values.add(roles.get(i - 1).getId());
            }
            builder.append("?" + i + ")");
            values.add(roles.get(i - 1).getId());
        }
        Query query = dao.createQuery(builder.toString());
        if (!values.isEmpty()) {
            for (int i = 0; i < values.size(); i++) {
                query.setParameter(i + 1, values.get(i));
            }
        }

        List<RestrictedUiElements> list = query.getResultList();
        if (list != null && list.size() > 0) {
            for (RestrictedUiElements el : list) {
                String subMenuOrForm = el.getSubMenuOrForm();
                if (StringUtils.isBlank(subMenuOrForm)) {
                    subMenuOrForm = "";
                }
                Map<String, String> map = results.get(subMenuOrForm);
                if (map == null) {
                    map = new HashMap<String, String>();
                    results.put(subMenuOrForm, map);
                }
                map.put(el.getPk().getNameorvalue(), el.getPk().getNameorvalue());
            }
        }
        return results;
    }
}
